<template>
  <div class="app-container">
    <!-- 故障字典 -->
    <!-- 查询和其他操作 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="设备名称">
        <div style="width: 220px;display:flex;justify-content:flex-end;align-items:center">
          <el-input v-model="listQuery.fequipmentname" clearable style="display: inline-block;width:200px" />
          <i style="display: inline-block;width:20px;color:#409EFF;margin-left:3px" class="el-icon-search" @click="searchDialog('search')"/>
        </div>
      </el-form-item>
      <el-form-item label="故障代码">
        <el-input
          v-model.number="listQuery.ferrorno"
          clearable
          class="filter-item"
          style="width: 200px"
          placeholder="请输入故障代码"
        />
      </el-form-item>
      <el-form-item label="故障名称">
        <el-input
          v-model="listQuery.fdangername"
          clearable
          class="filter-item"
          style="width: 200px"
          placeholder="请输入故障名称"
        />
      </el-form-item>
      <el-form-item label="故障等级">
        <el-select v-model="listQuery.ffaultno" filterable clearable class="filter-item" placeholder="请选择故障等级">
          <el-option
            v-for="item in getListffaultno"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <!-- v-permission="['fault:equipmentFault:read']" -->
        <el-button
          :style="{background:buttonColor.lookup,color:buttonColor.color}"
          round
          size="medium"
          class="filter-item"
          @click="handleFilter"
        >查找</el-button
        >
        <!-- v-permission="['fault:equipmentFault:create']" -->
        <el-button
          :style="{background:buttonColor.add,color:buttonColor.color}"
          round
          size="medium"
          class="filter-item"
          @click="handleCreate"
        >添加</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      :header-cell-style="tableColor"
      stripe
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column :width="buttonColor.operationTwo" align="center" label="操作" class-name="small-padding">
        <template slot-scope="scope">
          <div class="operationButton">
            <div :style="{color:buttonColor.edit,cursor:'pointer'}" @click="handleUpdate(scope.row)">
              <img src="../../../public/images/edit.png" >
              编辑
            </div>
            <div :style="{color:buttonColor.delete,cursor:'pointer'}" @click="handleDelete(scope.row)">
              <img src="../../../public/images/del.png" >
              删除
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :index="indexMethod"
        align="center"
        label="序"
        type="index"
      />
      <el-table-column align="center" label="设备编号" prop="feuipmentid" />
      <el-table-column :formatter="formatfeuipmentname" align="center" label="设备名称" prop="fequipmentname" />
      <el-table-column align="center" label="故障代码" prop="ferrorno" />
      <el-table-column align="center" label="故障名称" prop="fdangername" />
      <el-table-column :formatter="formatffaultno" align="center" label="故障等级" prop="ffaultno" />
      <el-table-column align="center" label="处理天数" prop="fprocday" />
      <el-table-column align="center" label="处理手册" prop="fprocword" />

    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      width="auto"
    >
      <template slot="title">
        <div :style="titleColor">{{ textMap[dialogStatus] }}</div>
      </template>
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="auto"
        style="width: 400px; margin: 0 30px"
      >
        <el-form-item label="设备编号" prop="feuipmentid">
          <div v-if="dialogStatus=='create'" style="display:flex;justify-content:flex-end;align-items:center">
            <el-input v-model="dataForm.feuipmentid" style="display: inline-block" />
            <i style="display: inline-block;width:20px;color:#409EFF;margin-left:3px" class="el-icon-search" @click="searchDialog('add')"/>
          </div>
          <el-input v-else v-model="dataForm.feuipmentid" disabled style="display: inline-block" />
        </el-form-item>
        <el-form-item label="设备名称" prop="fequipmentname">
          <el-input v-model="dataForm.fequipmentname" disabled style="display: inline-block" />
          <!-- <el-select disabled v-model="dataForm.feuipmentid" filterable clearable class="filter-item" placeholder="请选择设备名称">
          <el-option
            v-for="item in getListfeuipment"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select> -->
        </el-form-item>
        <el-form-item label="故障代码" prop="ferrorno">
          <el-input v-if="dialogStatus=='create'" v-model.number="dataForm.ferrorno" />
          <el-input v-else v-model.number="dataForm.ferrorno" disabled />
        </el-form-item>
        <el-form-item label="故障名称" prop="fdangername">
          <el-input v-model="dataForm.fdangername" />
        </el-form-item>
        <el-form-item label="故障等级" prop="ffaultno">
          <el-select v-model="dataForm.ffaultno" style="width:100%" filterable clearable class="filter-item" placeholder="请选择故障等级">
            <el-option
              v-for="item in getListffaultno"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"/>
          </el-select>
        </el-form-item>
        <el-form-item label="处理天数" prop="fprocday">
          <el-input v-model.number="dataForm.fprocday" />
        </el-form-item>
        <el-form-item label="处理手册" prop="fprocword">
          <el-input v-model="dataForm.fprocword" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="dialogFormVisible = false">取消</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          :style="{background:buttonColor.confirm,color:buttonColor.color}"
          @click="createData"
        >确定</el-button
        >
        <el-button v-else :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <!-- 设备搜索弹出框 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="searchVisible"
      top="5vh"
      title="搜索"
    >
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="设备编号">
          <el-input
            v-model="listQuerySearch.fequipmentno"
            clearable
            class="filter-item"
            style="width: 150px"
            placeholder="请输入设备编号"
          />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input
            v-model="listQuerySearch.fequipmentname"
            clearable
            class="filter-item"
            style="width: 150px"
            placeholder="请输入设备名称"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            :style="{background:buttonColor.lookup,color:buttonColor.color}"
            round
            size="medium"
            class="filter-item"
            icon="el-icon-search"
            @click="searchFilter"
          >查找</el-button
          >
        </el-form-item>
      </el-form>

      <!-- 查询结果 -->
      <el-table
        v-loading="listLoadingSearch"
        :data="searchList"
        :header-cell-style="tableColor"
        stripe
        element-loading-text="正在查询中。。。"
        border
        fit
        highlight-current-row
        height="300"
      >
        <el-table-column align="center" label="设备编号" prop="fequipmentno" />
        <el-table-column align="center" label="设备名称" prop="fequipmentname" />
        <el-table-column align="center" label="规格" prop="fspec" />
        <el-table-column
          align="center"
          label="选择"
          class-name="small-padding"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              round
              size="small"
              class="button-margin"
              @click="searchData(scope.row)"
            >确定</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="totalSearch > 0"
        :total="totalSearch"
        :page.sync="listQuerySearch.page"
        :limit.sync="listQuerySearch.limit"
        style="padding:14px 10px !important"
        @pagination="getSearchList"
      />
    </el-dialog>
  </div>
</template>

<style>
.button-margin {
  margin: 2px 0px;
}
.el-button + .el-button {
  margin-left: 1px;
}
</style>

<script>
import {
  listequipmentFault,
  createequipmentFault,
  updateequipmentFault,
  deleteequipmentFault
} from '@/api/equipmentFault'
import Pagination from '@/components/Pagination'
import moment from 'moment'
import { tableColor, titleColor, buttonColor } from '@/filters/index'
import { getListArea } from '@/api/area'
import { listinfo } from '@/api/info'

const siteTypeMap = {
  1: '设备1',
  2: '设备2',
  3: '设备3',
  4: '设备4',
  5: '设备5',
  6: '设备6',
  7: '设备7',
  8: '设备8',
  9: '设备9'
}

export default {
  name: 'STsEquipmentFault',
  components: { Pagination },
  filters: {
    siteTypeFilter(type) {
      return siteTypeMap[type]
    }
  },
  data() {
    return {
      buttonColor: buttonColor,
      getListfeuipment: [],
      searchFlag: null,
      searchVisible: false,
      searchList: null,
      listLoadingSearch: true,
      totalSearch: 0,
      listQuerySearch: {
        page: 1,
        limit: 20,
        fequipmentno: undefined,
        sort: 'create_time',
        order: 'desc'
      },

      getListffaultno: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        feuipmentid: undefined,
        fequipmentname: undefined,
        ferrorno: undefined,
        fdangername: undefined,
        ffaultno: undefined,
        fprocday: undefined,
        fprocword: undefined,
        fupddate: undefined,
        foperator: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      dataForm: {
        feuipmentid: undefined,
        fequipmentname: undefined,
        ferrorno: undefined,
        fdangername: undefined,
        ffaultno: undefined,
        fprocday: undefined,
        fprocword: undefined,
        fupddate: undefined,
        foperator: undefined,
        id: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      tableColor: tableColor,
      titleColor: titleColor,
      rules: {
        feuipmentid: [{ required: true, message: '设备编号不能为空' }],
        ferrorno: [
          { required: true, message: '故障代码不能为空' },
          { type: 'number', message: '故障代码必须为数字值', transform: (value) => Number(value) }
        ],
        fdangername: [],
        ffaultno: [{ type: 'number', message: '故障等级必须为数字值', transform: (value) => Number(value) }],
        fprocday: [{ type: 'number', message: '处理天数必须为数字值', transform: (value) => Number(value) }],
        fprocword: [],
        fupddate: [],
        foperator: []
      }
    }
  },
  created() {
    this.getList()
    this.getSearchList()
    getListArea({ flag: 19 })
      .then(response => {
        this.getListffaultno = response.data.data.list
      })
      .catch(() => {
        this.getListffaultno = []
      })

    listinfo()
      .then(response => {
        this.getListfeuipment = response.data.data.list
      })
      .catch(() => {
        this.getListfeuipment = []
      })
  },
  methods: {
    datetimeFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    // 获取搜索列表
    getSearchList() {
      this.listLoadingSearch = true
      listinfo(this.listQuerySearch)
        .then(response => {
          this.searchList = response.data.data.list
          this.totalSearch = response.data.data.total
          this.listLoadingSearch = false
        })
        .catch(() => {
          this.searchList = []
          this.totalSearch = 0
          this.listLoadingSearch = false
        })
    },

    searchFilter() {
      this.listQuerySearch.page = 1
      this.getSearchList()
    },

    // 搜索弹出框
    searchDialog(data) {
      this.searchFlag = data
      this.searchVisible = true
    },
    searchData(row) {
      this.searchVisible = false
      if (this.searchFlag === 'add') {
        this.dataForm.feuipmentid = row.feuipmentid
        this.dataForm.fequipmentname = row.fequipmentname
      } else {
        this.listQuery.fequipmentname = row.fequipmentname
        this.listQuery.feuipmentid = row.feuipmentid
      }
    },
    // 故障等级
    formatffaultno: function(row, column) {
      if (this.getListffaultno.length > 0) {
        for (let i = 0; i < this.getListffaultno.length; i++) {
          if (row.ffaultno == this.getListffaultno[i].value) {
            return this.getListffaultno[i].label
          }
        }
        return ''
      } else {
        return ''
      }
    },
    // 设备名称
    formatfeuipmentname: function(row, column) {
      if (this.getListfeuipment.length > 0) {
        for (let i = 0; i < this.getListfeuipment.length; i++) {
          if (row.feuipmentid == this.getListfeuipment[i].feuipmentid) {
            return this.getListfeuipment[i].fequipmentname
          }
        }
        return ''
      } else {
        return ''
      }
    },
    formatfeuipmentnameup: function(row, column) {
      if (this.getListfeuipment.length > 0) {
        for (let i = 0; i < this.getListfeuipment.length; i++) {
          if (row == this.getListfeuipment[i].feuipmentid) {
            return this.getListfeuipment[i].fequipmentname
          }
        }
        return ''
      } else {
        return ''
      }
    },
    getList() {
      this.listLoading = true
      if (this.listQuery.feuipmentid == '') {
        this.listQuery.feuipmentid = null
      }
      if (this.listQuery.fequipmentname == '') {
        this.listQuery.fequipmentname = null
        this.listQuery.feuipmentid = null
      }
      listequipmentFault(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        feuipmentid: undefined,
        fequipmentname: undefined,
        ferrorno: undefined,
        fdangername: undefined,
        ffaultno: undefined,
        fprocday: undefined,
        fprocword: undefined,
        fupddate: undefined,
        foperator: undefined,
        id: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      if (this.getListffaultno.length > 0) {
        this.dataForm.ffaultno = Number(this.getListffaultno[0].value)
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id
          this.dataForm.fupddate = new Date()
          createequipmentFault(this.dataForm)
            .then((response) => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加设备故障代码成功'
              })
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }
      })
    },
    handleUpdate(row) {
      row.feuipmentid = row.feuipmentid.toString()
      this.dataForm = Object.assign({}, row)
      this.dataForm.fequipmentname = this.formatfeuipmentnameup(row.feuipmentid)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id
          this.dataForm.fupddate = new Date()
          updateequipmentFault(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.ferrorno === this.dataForm.ferrorno && v.feuipmentid === this.dataForm.feuipmentid) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新设备故障代码成功'
              })
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否要删除设备故障代码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteequipmentFault(row)
          .then((response) => {
            this.$notify.success({
              title: '成功',
              message: '删除设备故障代码成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch((response) => {
            this.$notify.error({
              title: '失败',
              message: response.data.data
            })
          })
      })
    },
    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>
